package com.wuneng.commonlibrary.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.nfc.NfcAdapter;
import android.nfc.NfcManager;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import static android.net.ConnectivityManager.TYPE_ETHERNET;


/**
 * 跟网络相关的工具类
 *
 * 获取网络信息需要在AndroidManifest.xml文件中加入相应的权限。
 * <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
 * @author 汤家骏 2017-04-06
 *
 */
public class NetUtils
{
	private NetUtils()
	{
		/* 不能被实例化  */
		throw new UnsupportedOperationException("cannot be instantiated");
	}

	/**
	 * 判断网络连接状态并提示
	 */
	public static void networkState(Context context) {
		if (NetUtils.isMobileConnected(context)) {
			//			ToastUtils.showLong(context, "当前为2G/3G/4G网络,请注意您的流量哦");
		} else if (NetUtils.isWifiConnected(context)) {
			//			ToastUtils.showLong(context, "当前为WiFi连接,不用心疼您的流量哦");
		} else {
			//			ToastUtils.showLong(context, "当前无网络连接");
		}
	}
	/**
	 * 判断网络是否连接(包含MOBILE网络和WIFI)
	 * @param context
	 * @return
	 */
	public static boolean isNetworkConnected(Context context) {
	    if (context != null) {
	        ConnectivityManager mConnectivityManager = (ConnectivityManager) context
	                .getSystemService(Context.CONNECTIVITY_SERVICE);
	        NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
	        if (mNetworkInfo != null) {
	        	if(mNetworkInfo.isAvailable()){
	        		return mNetworkInfo.isAvailable();  
	        	}else{
	        		return false;
	        	}
	        }else{
        		return false;	
	        }  
	    } 
	    return false;  
	}
	/**
	 * 判断MOBILE网络是否可用
	 * @param context
	 * @return
	 */
	public static boolean isMobileConnected(Context context) {
		if (context != null) {
			ConnectivityManager mConnectivityManager = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo mMobileNetworkInfo = mConnectivityManager
					.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
			if (mMobileNetworkInfo != null) {
				 if(mMobileNetworkInfo.getState() == State.CONNECTED || mMobileNetworkInfo.getState() == State.CONNECTING){
				   return mMobileNetworkInfo.isAvailable();
				 	}
				}
			}
		return false;
	}
	/**
	 * 判断是否是wifi连接
	 */
	public static boolean isWifiConnected(Context context) {
	    if (context != null) {  
	        ConnectivityManager mConnectivityManager = (ConnectivityManager) context
	                .getSystemService(Context.CONNECTIVITY_SERVICE);
	        NetworkInfo mWiFiNetworkInfo = mConnectivityManager
	                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
	        if (mWiFiNetworkInfo != null) { 
	        	if(mWiFiNetworkInfo.getState() == State.CONNECTED || mWiFiNetworkInfo.getState() == State.CONNECTING){
	        		return mWiFiNetworkInfo.isAvailable();  
	        	}
	        }  
	    }  
	    return false;  
	}
	/**
	 *获取当前网络连接的类型信息
	 */
	public static int getConnectedType(Context context) {
    		if (context != null) {  
        		ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                	.getSystemService(Context.CONNECTIVITY_SERVICE);
       	 		NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
        	if (mNetworkInfo != null && mNetworkInfo.isAvailable()) {  
           		 return mNetworkInfo.getType();  
      		  	}  
   		 }  
   			 return -1;  
	}
	/**
	 * 打开网络设置界面
	 */
	@SuppressLint("NewApi") public static void openSetting(Activity activity){
		 Intent intent = null;
		/**
		 * 判断手机系统的版本！如果API大于10 就是3.0+
		 * 因为3.0以上的版本的设置和3.0以下的设置不一样，调用的方法不同
		 */
         if (android.os.Build.VERSION.SDK_INT > 10) {
			 //跳转到系统WIFI设置界面(安卓4.4.2下测试)
             intent = new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS);
         } else {  
             intent = new Intent();
             ComponentName component = new ComponentName(
                     "com.android.settings",  
                     "com.android.settings.WirelessSettings");  
             intent.setComponent(component);  
             intent.setAction("android.intent.action.VIEW");  
         }  
         activity.startActivity(intent);  
	}


	/**
	 * 判断NFC是否打开
	 * @param context
	 * @return
     */
	public static boolean hasNfc(Context context){
		boolean bRet=false;
		if(context==null)
			return bRet;
		NfcManager manager = (NfcManager) context.getSystemService(Context.NFC_SERVICE);
		NfcAdapter adapter = manager.getDefaultAdapter();
		if (adapter != null && adapter.isEnabled()) {
			// adapter存在，能启用
			bRet=true;
		}
		return bRet;
	}

	/**
	 * 判断有线网络
	 * @param context
	 * @return
     */
	public static boolean getEthernetState(Context context){
		ConnectivityManager conn = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo[] networkInfo = conn.getAllNetworkInfo();
		if(networkInfo != null) {
			for (int i = 0; i < networkInfo.length; i++) {
				if (networkInfo[i].getType() == TYPE_ETHERNET) {
					//有线网络连接成功
					return true;
				}else {
					return false;
				}
			}
		}

			return false;
	}

//	private static void EthernetStateListen() {
//		 IntentFilter mIntentFilter;
//		 final BroadcastReceiver mReceiver = new BroadcastReceiver(){
//			@Override
//			public void onReceive(Context context, Intent intent){
//				String action = intent.getAction();
//				// 当以太网状态改变
//				if (action.equals(EthernetDataTracker.ETHERNET_STATE_CHANGED_ACTION)){
//					// 取得当前以太网状态
//					int state = intent.getIntExtra(EthernetDataTracker.EXTRA_ETHERNET_STATE, 0);
//					// 根据当前以太网状态取得信息
//					switch (state) {
//						case EthernetDataTracker.ETHER_STATE_CONNECTED: //已连接
//
//							break;
//
//						case EthernetDataTracker.ETHER_STATE_DISCONNECTED: //未连接
//
//							break;
//					}
//
//				}
//			}
//		};
//	}

	//在java代码中执行adb命令
	public String execCommand(String command) {
		Runtime runtime;
		Process proc = null;
		StringBuffer stringBuffer = null;
		try {
			runtime = Runtime.getRuntime();
			proc = runtime.exec(command);
			stringBuffer = new StringBuffer();
			if (proc.waitFor() != 0) {
				System.err.println("exit value = " + proc.exitValue());
			}
			BufferedReader in = new BufferedReader(new InputStreamReader(
					proc.getInputStream()));

			String line = null;
			while ((line = in.readLine()) != null) {
				stringBuffer.append(line + " ");
			}

		} catch (Exception e) {
			System.err.println(e);
		} finally {
			try {
				proc.destroy();
			} catch (Exception e2) {
			}
		}
		return stringBuffer.toString();
	}
	//判断网线拔插状态
	//通过命令cat /sys/class/net/eth0/carrier，如果插有网线的话，读取到的值是1，否则为0
	public boolean isWirePluggedIn(){
		String state= execCommand("cat /sys/class/net/eth0/carrier");
		if(state.trim().equals("1")){  //有网线插入时返回1，拔出时返回0
			return true;
		}
		return false;
	}


}
